package com.dashan.servlets;

import static com.dashan.Constants.FRIENDNAME;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Optional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;

import com.dashan.backend.datastore.DsUserProfile;
import com.dashan.backend.datastore.UserDao;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetUserProfileServlet extends DashanPrivateServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(FRIENDNAME, Optional, String.class, 
                "This friend's profile will be returned, empty to return user's profile"));
        return res;
    }
    
    @Override
    public String getUrlPattern() {
        return "/getuserprofile";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            DsUserProfile profile;
            if (params.get(FRIENDNAME).hasValue()) {
                profile = 
                    dao.getUser(params.get(FRIENDNAME).stringValue()).getProfile();
            } else {
                profile = 
                    dao.getUser(params.get(USERNAME).stringValue()).getProfile();
            }
            
            Document xmlDoc = XmlHelper.createXmlDocument("profile");
            if (profile != null) {
                xmlDoc.getDocumentElement().appendChild(profile.getXmlElement(xmlDoc));
            }
            resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException(e.getMessage());
        } finally {
            dao.commit();
        }
    }
}
